import { doLoginApi, getMenusApi } from '@/api/userApi'
export default {
  namespaced: true,
  state: {
    userinfo: {
      id: 0,
      token: '',
      avatar: '',
      name: '',
      roleid: 0,
      routes: []
    },
    menus: [],
    auths: []
  },
  mutations: {
    // 登录成功后设置用户状态
    setUserInfo(state, payload) {
      state.userinfo = payload
    },
    setToken(state, payload) {
      state.userinfo.token = payload
    },
    // 用户退出
    logout(state, payload) {
      state.userinfo = {
        id: 0,
        token: '',
        avatar: '',
        name: '',
        roleid: 0,
        routes: []
      }
      state.menus = []
      state.auths = []
    },
    // 缓存菜单信息
    setMenus(state, payload) {
      state.menus = payload
    },
    setAuths(state, payload) {
      state.auths = payload
    }
  },
  actions: {
    async loginAction({ commit }, payload) {
      let ret = await doLoginApi(payload)
      if (ret.code === 0) {
        commit('setUserInfo', ret.data)
      }
      return ret.code
    },
    async fetchMenusAction({ commit, state }, payload) {
      // 缓存
      if (state.menus.length === 0) {
        let ret = await getMenusApi(payload)
        commit('setMenus', ret.data.menus)
        commit('setAuths', ret.data.auths)
      }
    }
  }
}
